﻿dataService = {};
dataService.config = {
    localDebug: false,
    saveRequest: false
};
dataService.saveLog = function (fileName, logContent) {
    var servicePath = SysConstant.Service.ServicePath + SysConstant.Service.SaveLogFunctionName;
    $.ajax({
        type: "POST",
        url: servicePath,
        data: { fileName: fileName, logContent: logContent },
        async: false
    });
    return true;
};
dataService.getData = function (taskGuid, dataGuid, dataType) {
    var result = null;
    var serviceLog = "Get_" + taskGuid + "_" + dataType + "_" + dataGuid + ".txt";
    var servicePath = null;
    if (dataService.config.localDebug) {
        servicePath = SysConstant.Service.LocalPath + serviceLog;
        $.ajax({
            type: "GET",
            url: servicePath,
            async: false,
            success: function (request, textStatus) {
                result = request;
            },
            error: function (request, textStatus) {
                utility.message.promptCallBackendError("载入【" + servicePath + "】出错");
            }
        });
    }
    else {
        servicePath = SysConstant.Service.ServicePath + SysConstant.Service.GetDataFunctionName;
        $.ajax({
            type: "POST",
            url: servicePath,
            data: { UserID: Session.LoginUser().UserGuid, TaskGuid: taskGuid, DataGuid: dataGuid, DataType: dataType },
            async: false,
            cache: false,
            success: function (request, textStatus) {
                result = request.text;
                if (dataService.config.saveRequest) {
                    dataService.saveLog(serviceLog, result);
                }
            },
            error: function (request, textStatus) {
                utility.message.promptCallBackendError("GetData: [TaskGuid=" + taskGuid + ",DataGuid=" + dataGuid + ",DataType=" + dataType + "]");
            }
        });
    }
    return result;
};
dataService.setData = function (taskGuid, dataGuid, dataType, xmlData) {
    var result = null;
    var serviceLog = "";
    var servicePath = null;
    if (dataService.config.saveRequest) {
        serviceLog = "Set_" + taskGuid + "_" + dataType + "_" + dataGuid + ".txt";
        dataService.saveLog(serviceLog, xmlData);
    }
    if (dataService.config.localDebug) {
        result = 0;
    }
    else {
        servicePath = SysConstant.Service.ServicePath + SysConstant.Service.SetDataFunctionName;
        result = null;
        $.ajax({
            type: "POST",
            url: servicePath,
            data: { UserID: Session.LoginUser().UserGuid, TaskGuid: taskGuid, DataGuid: dataGuid, DataType: dataType, XmlData: xmlData },
            async: false,
            success: function (request, textStatus) {
                result = request.text;
            },
            error: function (request, textStatus) {
                //alert("服务器错误，请联系管理员!");
                utility.message.promptCallBackendError("SetData: [TaskGuid=" + taskGuid + ",DataGuid=" + dataGuid + ",DataType=" + dataType + ",XmlData=" + xmlData + "]");
                result = -1;
            }
        });
    }
    return result;
};
dataService.transformData = function (taskGuid, xmlParam) {
    var result = null;
    var servicePath = null;
    var localParam = xmlParam.replace(/ /g, "").replace(/[<\/\\:\*\?"'|>]/g, "").substring(65, 150);
    var serviceLog = "Txm_" + taskGuid + "_" + localParam + ".txt";
    if (dataService.config.localDebug) {
        servicePath = SysConstant.Service.LocalPath + escape(serviceLog);
        $.ajax({
            type: "GET",
            url: servicePath,
            async: false,
            success: function (request, textStatus) {
                result = request;
            },
            error: function (request, textStatus) {
                utility.message.promptCallBackendError("载入【" + servicePath + "】出错");
            }
        });
    }
    else {
        servicePath = SysConstant.Service.ServicePath + SysConstant.Service.TransformFunctionName;
        var xmlResult = document.createElement("xml");
        $.ajax({
            url: servicePath,
            type: "POST",
            data: { UserID: Session.LoginUser().UserGuid, TaskGuid: taskGuid, XmlTransform: xmlParam },
            async: false,
            cache: false,
            success: function (request, textStatus) {
                result = request.text;
                if (dataService.config.saveRequest) {
                    dataService.saveLog(serviceLog, result);
                }
            },
            error: function (request, textStatus) {
                utility.message.promptCallBackendError("TransformData: [TaskGuid=" + taskGuid + ",XmlTransform=" + xmlParam + "]");
            }
        });
    }
    return result;
};
dataService.getCacheTransform = function (taskGuid, cacheName, xmlParam) {
    var cacheFile = taskGuid + "_cache_" + cacheName + ".txt";
    var cacheContent = dataService.getPage("/Local/" + cacheFile);
    if (cacheContent == null) {
        cacheContent = dataService.transformData(taskGuid, xmlParam);
        dataService.saveLog(cacheFile, cacheContent);
    }
    return cacheContent;
}
dataService.delDataList = function (taskGuid, dataGuidList, dataType) {
    var delTemplate = "";
    var result = 0;
    var dataList = dataGuidList.split(",");
    for (var i in dataList) {
        delTemplate = SysConstant.Common.DelStr.replace("{0}", taskGuid).replace("{1}", dataList[i]).replace("{2}", dataType);
//        delTemplate = Constant.SysTemplate.OrgInfo.DelStr.replace("{0}", dataList[i]).replace("{1}", dataType);
        result += parseInt(dataService.setData(taskGuid, dataList[i], dataType, delTemplate));
    }
    return result;
};
dataService.delData = function (userId, taskGuid, dataGuid, dataType) {
    var delTemplate = "<Documents>";
    delTemplate += Constant.SysTemplate.OrgInfo.DelStr.replace("{0}", dataGuid).replace("{1}", dataType);
    delTemplate += "</Documents>";
    var result = dataService.setData(null, SysConstant.TaskGuid.OrgInfo, dataGuid, dataType, delTemplate);
    return result;
};
dataService.fillNewGuid = function (xmlText, tagName) {
    xmlTemplate = $(utility.xml.convertXmlStringToDoc(xmlText));
    guidText = dataService.getNewGuid();
    xmlTemplate.find("Document").attr("DataGuid", guidText);
    xmlTemplate.find(tagName).text(guidText);
    return xmlTemplate;
};
dataService.getNewGuid = function () {
    var result = null;
    //    var newGuidResult = dataService.getData(SysConstant.TaskGuid.GlobalInfo, Constant.SysDataGuid.GlobalInfo.InitInfo, Constant.SysDataType.GlobalInfo.NewGuid);
    //    if (newGuidResult) {
    //        var guidXml = $(utility.xml.convertXmlStringToDoc(newGuidResult));
    //        result = guidXml.find("Guid").text();
    //    }
    $.ajax({
        url: "/Handler/GetNewGuid.ashx",
        type: "GET",
        async: false,
        cache: false,
        success: function (request, textStatus) {
            result = request;
        },
        error: function (request, textStatus) {
            result = "";
            utility.message.promptCallBackendError("获取guid失败");

        }
    });
    return result;
};
dataService.getApplyformID = function (typeToApply, userId) {
    $formIDText = dataService.getData(SysConstant.TaskGuid.ExtComponent, typeToApply, Constant.SysDataType.UsrIntr.SysSequence);
    return $(utility.xml.convertXmlStringToDoc($formIDText)).find("DataSequence").text();
};
dataService.getPage = function (pageUrl) {
    var result = null;

    $.ajax({
        type: "GET",
        url: encodeURI(pageUrl),
        contentType: "text/html; charset=UTF-8",
        dataType: "text",
        //data: { UserID: Session.LoginUser().UserGuid, TaskGuid: taskGuid, DataGuid: dataGuid, DataType: dataType },
        async: false,
        cache: false,
        success: function (request, textStatus) {
            result = request;
        },
        error: function (request, textStatus) {
            result = null;
        }
    });
    return result;
};
dataService.delFile = function (fileGuid, filePath) {
    if (!filePath || filePath == "") return false;
    var result = false;
    $.ajax({
        type: "POST",
        url: "/Handler/DeleteFileHandler.ashx",
        async: false,
        data: { filePath: filePath },
        success: function (request, textStatus) {
            var delResult = dataService.delDataList(PrjConstant.PrjTaskGuid.FeeMgr, fileGuid, PrjConstant.GLC.FeeMgr.FileAttachment.DataType);
            //$.messager.alert("", taskGuid + "_" + dataType + "_" + dataGuid + ":" + request.text);
            if (delResult == 0)
                result = true
        },
        error: function (request, textStatus) {
            //alert("服务器错误，请联系管理员!");
            result = false;
        }
    });
    return result;
};


// XML process
utility = {};
utility.xml = {
    //    getXMLDoc: function (xml) {
    //        var xmlDoc = null;
    //        try //Internet Explorer
    //            {
    //            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    //            xmlDoc.async = "false";
    //            xmlDoc.loadXML(xml);
    //        }
    //        catch (e) {
    //            try //Firefox, Mozilla, Opera, etc.
    //                   {
    //                parser = new DOMParser();
    //                xmlDoc = parser.parseFromString(xml, "text/xml");
    //            }
    //            catch (e) { }
    //        }
    //        return xmlDoc;
    //    },
    convertXmlStringToDoc: function (xmlStr) {
        if (xmlStr.length == 0) {
            xmlStr = "<Document/>";
        }
        //var xmlDoc = $.loadXML(xmlStr);
        var xmlDoc = $.parseXML(xmlStr);
        var xml = $(xmlDoc);
        return xml;
    },
    convertXmlDocToString: function (xmlDoc) {
        if (navigator.appVersion.match(/9./i) == "9.") {
            return new XMLSerializer().serializeToString(xmlDoc[0]);
        } else {
            return xmlDoc[0].xml;
        }
    },
    convertXmlStringToGridJson: function (xmlString, matchNodeName, fieldList) {
        var dataList = $(xmlString).find(matchNodeName);
        var records = [];
        var fields = fieldList.split(",");
        if (fields.length > 0 && dataList.length > 0) {
            dataList.each(function (i, n) {
                var record = {};
                for (var f in fields) {
                    record[fields[f]] = $(n).find(fields[f]).text();
                }
                records.push(record);
            });
        }
        return { total: dataList.length, rows: records };
    },
    fillHtmlContainerInputsWithXmlDoc: function (xml, tableId) {
        var doms = $(tableId).find(":input");
        doms.each(function (i, n) {
            var inputId = $(n).attr("id");
            if (inputId == undefined)
                return;
            var tagName = inputId.split("_")[1];
            var tagValue = xml.find(tagName).text();
            utility.control.setInputValue("#" + inputId, tagValue);
        });
    },
    fillXmlDocWithHtmlContainer: function (containerId, xmlDoc) {
        var doms = $(containerId).find(":input");
        doms.each(function (i, n) {
            var inputId = $(n).attr("id");
            if (inputId == undefined)
                return;
            var inputValue = utility.control.getInputValue($(n));
            var tagList = inputId.split("_");
            var tagName = tagList.length > 2 ? tagList[2] : tagList[1];
            //alert(tagName + "=" + inputValue);
            xmlDoc.find(tagName).text(inputValue);
        });
        return xmlDoc;
    }
};
utility.xml.fillXmlStringWithHtmlContainer = function (containerId, xmlString){
    var xmlDoc = utility.xml.convertXmlStringToDoc(xmlString);
    xmlDoc = utility.xml.fillXmlDocWithHtmlContainer(containerId,xmlDoc);
    return utility.xml.convertXmlDocToString(xmlDoc);
};
utility.control = {
    getInputValue: function (inputControl) {
        var result = null;
        if (inputControl.attr("id") != undefined) {
            if (inputControl.length > 0) {
                var inputClass = inputControl.attr("class");
                if (inputClass == undefined) return null;
                if (inputClass.search("-codecombo") != -1) {
                    result = inputControl.combobox("getValue");
                } else if (inputClass.search("-combo") != -1) {
                    result = inputControl.combo("getValue");
                } else if (inputClass.search("-datebox") != -1) {
                    result = inputControl.datebox("getValue");
                } else if (inputClass.search("-codeMulticombo") != -1) {
                    result = inputControl.combotree("getValue");
                }
                else if (inputClass.search("-branchcombo") != -1) {
                    result = inputControl.combo("getValue");
                } else {
                    result = inputControl.val();
                }
            }
        }
        return result;
    },
    setInputValue: function (inputId, newValue) {
        var inputControl = $(inputId);
        if (inputControl.attr("id") != undefined) {
            try {
                $.each(inputControl, function (i, n) {
                    var inputClass = $(n).attr("class");
                    if (inputClass.search("-codecombo") != -1) {
                        $(n).combobox("setValue", newValue);
                    } else if (inputClass.search("-codeMulticombo") != -1) {
                        inputControl.combo("setValue", newValue);
                    } else if (inputClass.search("-combo") != -1) {
                        $(n).combo("setValue", newValue);
                    } else if (inputClass.search("-datebox") != -1) {
                        $(n).datebox("setValue", newValue);
                    } else if (inputClass.search("-branchcombo") != -1) {
                        $(n).combo("setValue", newValue);
                        var bindFieldName = $(n).branchcombo("getBindField");
                        if (bindFieldName) {
                            $(n).combo("setText", $(bindFieldName).val());
                        }
                    } else {
                        $(n).val(newValue);
                    }
                });
            }
            catch (err) {
                //utility.message.promptCallBackendError("页面设置错误：" + inputId + " => " + newValue);
            }
        }
    },
    resetInput: function (parentId) {
        var doms = $(parentId).find(":input");
        doms.each(function (i, n) {
            //alert($(n).attr("id"));
            //        if (!n.visiable)
            //            return;
            var className = $(n).attr("class");
            if (className == undefined)
                return;
            if (className.search("easyui-validatebox") != -1) {
                $(n).val("");
            }
            else if (className.search("combobox") != -1) {
                $(n).combobox("select", "");
            }
            else if (className.search("combotree") != -1) {
                $(n).combotree("setText", "");
                $(n).combotree("setValue", "");
            }
            else if (className.search("numberspinner") != -1) {
                $(n).val("");
            }
            else if (className.search("easyui-datebox") != -1) {
                $(n).datebox("clear");
            }
            else if (className.search("-codeMulticombo") != -1) {
                $(n).combo("setValue", "");
                $(n).combo("setText", "");
            }
            else if (className.search("-branchcombo") != -1) {
                $(n).combo("setValue", "");
                $(n).combo("setText", "");
            }
        });
    },
    initResetBtn: function (resetBtnId, tableId) {
        if ($(resetBtnId) == undefined) return;
        $(resetBtnId).click(function () {
            utility.control.resetInput(tableId);
        });
    },
    initCodeCombo: function (comboId, codeCategory, parentGuid, includeSubCode) {
        var $codeJson = getChildrenNodeData(codeCategory, parentGuid, includeSubCode);
        if (!includeSubCode) {
            $(comboId).combotree({
                onBeforeExpand: function (node) {
                    var $deptTree = $(comboId).combotree("tree");
                    var $childList = $deptTree.tree("getChildren", node.target);
                    $.each($childList, function (i, n) {
                        $deptTree.tree("remove", $childList[i].target);
                    });
                    $(comboId).combotree("tree").tree("append", { parent: node.target, data: getChildrenNodeData(codeCategory, node.id, false) });
                }
            });
        }
        $(comboId).combotree({
            panelWidth: '200',
            height: 'auto'
        });
        if (comboId == "#ApprovalTypeList")
            $codeJson.push({ "id": "SELFDEFINE", "text": "--自定义--" });
        $(comboId).combotree("loadData", $codeJson);
    },
    convertJsonToTable: function (jsonData, tableId) {
        var doms = $(tableId).find(":input");
        doms.each(function (i, n) {
            var inputId = $(n).attr("id");
            if (inputId == undefined)
                return;
            var tagName = inputId.split("_")[1];
            var tagValue = jsonData[tagName];
            utility.control.setInputValue("#" + inputId, tagValue);
        });
    },
    getFunctionOwner: function (functionName) {
        var owner = window;
        while (owner != undefined && owner != null) {
            if (owner[functionName])
                break;
            if (owner.location == owner.parent.location) {
                owner = null;
                break;
            }
            if (typeof owner == "DispHTMLDocument") {
                owner = owner.parentWindow;
            } else {
                owner = owner.parent;
            }
//            owner = owner.parentWindow;
        }
        return owner;
    },
    image: {
        uploadImage: function (imgSrc) {
            var result = "";
            $.ajax({
                type: "POST",
                url: "/Handler/ImgHandler.ashx",
                data: { ImgSrc: imgSrc, ActionCode: "Upload" },
                async: false,
                cache: false,
                success: function (request, textStatus) {
                    result = request;

                },
                error: function (request, textStatus) {
                    result = null;
                }
            });
            return result;
        },
        getPath: function (obj) {
            if (obj) {
                if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
                    obj.select();
                    return document.selection.createRange().text;
                }
                else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
                    if (obj.files) {
                        return obj.files.item(0).getAsDataURL();
                    }
                    return obj.value;
                }
                return obj.value;
            }
        }
    }
};
utility.page = {
    addMainTab: function (tabTitle, tabHref, options, parameters) {
        var owner = utility.control.getFunctionOwner("_addMainTab");
        if (owner != null) owner["_addMainTab"](tabTitle, tabHref, options, parameters);
    },
    closeTab: function () {
        var owner = utility.control.getFunctionOwner("_closeTab");
        if(owner!=null) owner["_closeTab"]();
    },
    pageParameter: function (options, param) {
        var owner = utility.control.getFunctionOwner("_pageParameter");
        if (owner != null) owner["_pageParameter"](options, param);
    },
    popupDialog: function (parentTabTitle, options, param) {
        var owner = utility.control.getFunctionOwner("_popupDialog");
        if (owner != null) owner["_popupDialog"](parentTabTitle, options, param);
    },
    closeDialog: function (refreshParent) {
        var owner = utility.control.getFunctionOwner("_closeDialog");
        if (owner != null) owner["_closeDialog"](refreshParent);
    },
    getCurrentTabTitle: function () {
        var owner = utility.control.getFunctionOwner("_getCurrentTabTitle");
        return (owner!=null) ? owner["_getCurrentTabTitle"]() : null;
    },
    refreshPanel: function (panelTitle, operationType, operationTarget, isOperationSuccess) {
        var owner = utility.control.getFunctionOwner("_refreshPanel");
        if (owner != null) owner["_refreshPanel"](panelTitle, operationType, operationTarget, isOperationSuccess);
    },
    promptOperationResult: function (operationType, operationTarget, isOperationSuccess) {
        var owner = utility.control.getFunctionOwner("_promptOperationResult");
        if (owner != null) owner["_promptOperationResult"](operationType, operationTarget, isOperationSuccess);
    },
    getQueryString: function (paramName) {
        var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
};
//utility.sysCode = {
//    getNodeData: function (codeCategory, parentGuid, includeSubCode) {
//        function getChildrenNodes($parentNode, includeSubCode) {
//            var $codeJson = [];
//            var $childCountTemp = "({0})";
//            var $codeText = "";
//            $($parentNode.find("SubCodesList")[0]).find(">SubCode").each(function (i, n) {
//                $childCount = $(n).find("SubChildCount").eq(0).text();
//                $codeJson.push({
//                    "CodeGuid": $(n).find("CodeGuid").eq(0).text(),
//                    "CodeName": $(n).find("CodeName").eq(0).text(),
//                    "CodeValue": $(n).find("CodeValue").eq(0).text(),
//                    "CodeOrder": $(n).find("CodeOrder").eq(0).text(),
//                    "state": ($childCount == "0" ? undefined : "closed"),
//                    "children": (includeSubCode && $childCount != "0" ? getChildrenNodes($(n), includeSubCode) : undefined)
//                });
//            });
//            return $codeJson;
//        }

//        var $codeSearchTemp = Constant.SysTemplate.UsrIntr.SysCodeList.replace("{0}", codeCategory).replace("{1}", parentGuid).replace("{2}", includeSubCode);
//        var $codeDataText = dataService.transformData(SysConstant.TaskGuid.ExtComponent, $codeSearchTemp);
//        var $codeDataXml = utility.xml.convertXmlStringToDoc($codeDataText);
//        var $codeList = $codeDataXml.find("Document");
//        if ($codeList.length > 0) {
//            return getChildrenNodes($codeList, includeSubCode);
//        } else {
//            return undefined;
//        }
//        //        var $codeJson = [];
//        //        var $childCountTemp = "({0})";
//        //        var $childCount = "";
//        //        var $codeText = "";
//        //        if ($codeList != null) {
//        //            $codeList.each(function (i, n) {
//        //                $childCount = $(n).find("SubChildCount").eq(0).text();
//        //                // $codeText = $(n).find("CodeValue").eq(0).text() + $childCountTemp.replace("{0}", $childCount);
//        //                $codeText = $(n).find("CodeValue").eq(0).text();
//        //                $codeJson.push({
//        //                    "CodeGuid": $(n).find("CodeGuid").eq(0).text(),
//        //                    "CodeName": $(n).find("CodeName").eq(0).text(),
//        //                    "CodeValue": $(n).find("CodeValue").eq(0).text(),
//        //                    "CodeOrder": $(n).find("CodeOrder").eq(0).text(),
//        //                    "state": ($childCount == "0" ? undefined : "closed"),
//        //                    "children": (includeSubCode || $childCount == "0" ? utility.sysCode.getNodeData($(n)) : undefined)
//        //                });


//        //                //                if (includeSubCode) {
//        //                //                    if ($childCount == "0")
//        //                //                        $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $(n).find("CodeValue").eq(0).text(), "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//        //                //                    else
//        //                //                        $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $codeText, "state": "closed", "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text(), "children": getChildrenNode($(n)) });
//        //                //                }
//        //                //                else {
//        //                //                    if ($childCount == "0")
//        //                //                        $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $(n).find("CodeValue").eq(0).text(), "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//        //                //                    else
//        //                //                        $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $codeText, "state": "closed", "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//        //                //                }
//        //            });
//        //        }
//        //        return $codeJson;
//    }
//}
utility.message = {
    alertMessage: function (result, windowName) {
        if (result == "0") {
            $.messager.show({
                title: "信息提示",
                msg: "保存成功"
            });
            $(windowName).window("close");
        }
        else {
            $.messager.show({
                title: "信息提示",
                msg: "保存失败"
            });
        }
    },
    popupMessage: function (popMsg) {
    },
    sysError: function (e) {
        $.messager.alert("系统错误", "系统错误，请记录错误信息并联系管理人员。<br><br>错误信息如下：<hr>" + e);
    },
    promptCallBackendError: function (errMsg) {
        $.messager.alert("系统错误", "系统错误，请记录错误信息并联系管理人员。<br><br>错误信息如下：<hr>" + errMsg);
    },
    promptOperationResult: function (operationType, operationTarget, isOperationSuccess) {
        var d = new Date();
        var h = d.getHours();
        var m = d.getMinutes();
        var se = d.getSeconds();
        var curTime = (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (se < 10 ? "0" + se : se);
        //alert(curTime);
        $.messager.show({
            title: '操作结果提醒',
            msg: curTime + '：【' + operationTarget + '】' + operationType + (isOperationSuccess ? '成功' : '失败'),
            showType: 'slide',
            timeout: 3000
        });
    }
};


//function getChildrenNodeData(codeCategory, parentGuid, includeSubCode) {
//    var $codeSearchTemp = Constant.SysTemplate.UsrIntr.SysCodeList.replace("{0}", codeCategory).replace("{1}", parentGuid).replace("{2}", includeSubCode);
//    var $codeDataText = dataService.transformData(SysConstant.TaskGuid.ExtComponent, $codeSearchTemp);
//    var $codeDataXml = utility.xml.convertXmlStringToDoc($codeDataText);
//    var $codeList = $codeDataXml.find("Document>SubCodesList>SubCode");
//    var $codeJson = [];
//    var $childCountTemp = "({0})";
//    var $childCount = "";
//    var $codeText = "";
//    if ($codeList != null) {
//        $codeList.each(function (i, n) {
//            $childCount = $(n).find("SubChildCount").eq(0).text();
//            // $codeText = $(n).find("CodeValue").eq(0).text() + $childCountTemp.replace("{0}", $childCount);
//            $codeText = $(n).find("CodeValue").eq(0).text();
//            if (includeSubCode) {
//                if ($childCount == "0")
//                    $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $(n).find("CodeValue").eq(0).text(), "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//                else
//                    $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $codeText, "state": "closed", "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text(), "children": getChildrenNode($(n)) });
//            }
//            else {
//                if ($childCount == "0")
//                    $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $(n).find("CodeValue").eq(0).text(), "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//                else
//                    $codeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $codeText, "state": "closed", "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//            }
//        });
//    }
//    return $codeJson;
//}

//function getChildrenNode($parentNode) {
//    var $subCodeJson = [];
//    var $childCountTemp = "({0})";
//    var $codeText = "";
//    $($parentNode.find("SubCodesList")[0]).find(">SubCode").each(function (i, n) {
//        $childCount = $(n).find("SubChildCount").eq(0).text();
//        // $codeText = $(n).find("CodeValue").eq(0).text() + $childCountTemp.replace("{0}", $childCount);
//        $codeText = $(n).find("CodeValue").eq(0).text();
//        if ($childCount == "0")
//            $subCodeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $(n).find("CodeValue").eq(0).text(), "text": $(n).find("CodeName").eq(0).text(), "order": $(n).find("CodeOrder").eq(0).text() });
//        else
//            $subCodeJson.push({ "id": $(n).find("CodeGuid").eq(0).text(), "name": $codeText, "state": "closed", "text": $(n).find("CodeName").eq(0).text(), "children": getChildrenNode($(n)), "order": $(n).find("CodeOrder").eq(0).text() });
//    });
//    return $subCodeJson;
//}

//function getTreeData(codeCategory, parentGuid) {
//    var $codeSearchTemp = Constant.SysTemplate.UsrIntr.SysCodeList.replace("{0}", codeCategory).replace("{1}", parentGuid).replace("{2}", false);
//    var $codeDataText = dataService.transformData(SysConstant.TaskGuid.ExtComponent, $codeSearchTemp);
//    var $codeDataXml = utility.xml.convertXmlStringToDoc($codeDataText);
//    var $codeList = $codeDataXml.find("Document>SubCodesList>SubCode");
//    var $codeJson = { total: 0, rows: [] };
//    var $childCountTemp = "({0})";
//    var $childCount = "";
//    if ($codeList != null) {
//        $codeJson.total = $codeList.length;
//        $codeList.each(function (i, n) {
//            $codeJson.rows.push({ CodeGuid: $(n).find("CodeGuid").eq(0).text(), CodeValue: $(n).find("CodeValue").eq(0).text() });
//        });
//    }
//    return $codeJson;
//}

//function translateForBool(logicalType) {
//    var strLogic = logicalType.toString().toLowerCase();
//    if (strLogic == "true")
//        return "是";
//    else if (strLogic == "false")
//        return "否";
//    else
//        return "";
//}

//function isLeafNode(treeId, node) {
//    if (node == null || node == undefined)
//        return false;
//    var result = true;
//    $rootsList = $(treeId).tree("getRoots");
//    $.each($rootsList, function (i, n) {
//        if (n.id == node.id) {
//            result = false;
//            return false;
//        }
//    });
//    return result;
//}

//function delUnitRecord(dataGuid, dataType) {
//    $delStr = "<Documents>";
//    $delStr += Constant.SysTemplate.OrgInfo.DelStr.replace("{0}", dataGuid).replace("{1}", dataType);
//    $delStr += "</Documents>";
//    var result = platform.setData(null, SysConstant.TaskGuid.OrgInfo, dataGuid, dataType, $delStr);
//    return result;
//}

//function initCompanyGrid() {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, Constant.SysDataGuid.OrgInfo.CompanyListGuid, Constant.Identify.CompanyList);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    $list = $xml.find("OUDataInfo");
//    $json = { total: $list.length, rows: [] };
//    $list.each(function (i, n) {
//        $json.rows.push({ GUID: $(n).attr("GUID"), Name: $(n).attr("Name") });
//    });
//    $("#companyList").datagrid("loadData", $json);
//}

//function initComboForCompanyList(comboId, companyId, parentId) {
//    $(comboId).combotree({
//        panelWidth: 250,
//        panelHeight: 250,
//        onSelect: function (node) {
//            if (companyId != undefined && companyId != "" && parentId != undefined && parentId != "") {
//                $deptTree = $(comboId).combotree("tree");
//                if ($deptTree.tree("getParent", node.target) == undefined) {
//                    $(companyId).val(node.id);
//                    $(parentId).val("");
//                }
//                else {
//                    $(companyId).val($deptTree.tree("getRoot").id);
//                    $(parentId).val(node.id);
//                }
//            }
//        },
//        onDblClick: function (node) { },
//        onBeforeExpand: function (node) {
//            $deptTree = $(comboId).combotree("tree");
//            $childList = $deptTree.tree("getChildren", node.target);
//            $.each($childList, function (i, n) {
//                $deptTree.tree("remove", $childList[i].target);
//            });
//            $deptTree.tree("append", { parent: node.target, data: getBrachNodes(node.id) });
//        }
//    });
//    $(comboId).combotree("loadData", getCompanyNodes());
//}

//function getCompanyNodes() {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, Constant.SysDataGuid.OrgInfo.CompanyListGuid, Constant.Identify.CompanyList);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    $list = $xml.find("OUDataInfo");
//    $json = [];
//    $list.each(function (i, n) {
//        $json.push({ "id": $(n).attr("GUID"), "text": $(n).attr("Name"), "state": "closed" });
//    });
//    return $json;
//}

//function getBrachNodes(companyGuid) {
//    $childNew = dataService.getData(SysConstant.TaskGuid.OrgInfo, companyGuid, Constant.Identify.BranchList);
//    $childNewList = utility.xml.convertXmlStringToDoc($childNew).find("OUDataInfo");
//    $childNodes = [];
//    $childNewList.each(function (i, n) {
//        $childGuid = $(n).attr("GUID");
//        if (hasChildNode($childGuid))
//            $childNodes.push({ "id": $(n).attr("GUID"), "text": $(n).attr("Name"), "state": "closed" });
//        else
//            $childNodes.push({ "id": $(n).attr("GUID"), "text": $(n).attr("Name") });
//    });
//    return $childNodes;
//}

//function removeChildNodes(treeID, nodeTarget) {
//    $childList = $(treeID).tree("getChildren", nodeTarget);
//    for (var i = 0; i < $childList.length; i++) {
//        $(treeID).tree("remove", $childList[i].target);
//    }
//}

//function hasChildNode(branchGuid) {
//    $childNew = dataService.getData(SysConstant.TaskGuid.OrgInfo, branchGuid, Constant.Identify.BranchList);
//    $childNewList = utility.xml.convertXmlStringToDoc($childNew).find("OUDataInfo");
//    return $childNewList.length > 0
//}

//function getMemberList(deptGuid) {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, deptGuid, Constant.Identify.BranchMemberList);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    $list = $xml.find("OUDataInfo");
//    $json = { total: $list.length, rows: [] };
//    $list.each(function (i, n) {
//        $json.rows.push({ Guid: $(n).attr("GUID"), Name: $(n).attr("NAME") });
//    });
//    return $json;
//}

//function getMemberName(memberGuid) {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, memberGuid, Constant.Identify.Member);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    return $xml.find("Name").text();
//}

//function getMemberDetailList(deptGuid, deptName) {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, deptGuid, Constant.SysDataType.OrgInfo.BranchMemberList);
//    if ($data == null) return { total: 0, rows: [] }; ;
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    $list = $xml.find("OUDataInfo");
//    $json = { total: $list.length, rows: [] };
//    $list.each(function (i, n) {
//        $json.rows.push({ Guid: $(n).attr("GUID"),
//            Name: $(n).attr("Name")
//        });
//    });
//    return $json;
//}
//function getCompanyName(companyGuid) {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, companyGuid, Constant.Identify.Company);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    return $xml.find("Name").text();

//}
//function getBranchName(branchGuid) {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, branchGuid, Constant.Identify.Branch);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    return $xml.find("Name").text();
//}

//function getDicForAllBranch() {
//    $companyJson = getCompanyNodes();
//    $deptJson = $companyJson;
//    for (var i = 0; $companyJson != undefined && i < $companyJson.length; i++) {
//        $branchJsonNew = getBrachNodes($companyJson[i].id);
//        $deptJson = $deptJson.concat($branchJsonNew);
//    }
//    return $deptJson;
//}

//function convertArrayToDic(oldArray) {
//    if (oldArray == undefined || oldArray == null) return;
//    var nArray = new Array();
//    for (var i = 0; i < oldArray.length; i++) {
//        nArray[oldArray[i].id] = oldArray[i].text;
//    }
//    return nArray;
//}
//String.prototype.Trim = function () {
//    return this.replace(/(^\s*)|(\s*$)/g, "");
//}
//String.prototype.LTrim = function () {
//    return this.replace(/(^\s*)/g, "");
//}
//String.prototype.RTrim = function () {
//    return this.replace(/(\s*$)/g, "");
//}
//function getChangeDetail(fieldName, oldValue, newValue) {
//    var changeDetail = "";
//    changeDetail += "<Field>";
//    changeDetail += "<FieldName>" + fieldName + "</FieldName>";
//    changeDetail += "<OldValue>" + oldValue + "</OldValue>";
//    changeDetail += "<NewValue>" + newValue + "</NewValue>";
//    changeDetail += "</Field>";
//    return changeDetail;
//}

//function initDepart() {
//    var $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, Constant.SysDataGuid.OrgInfo.CompanyListGuid, Constant.Identify.CompanyList);
//    var $xml = utility.xml.convertXmlStringToDoc($data);
//    var $list = $xml.find("OUDataInfo");
//    return pushChildList($list,true);
//}
//function pushChildList($list,isCompany) {
//    var $departJson = [];
//    if (!$list.length > 0)
//        return;
//    $list.each(function (i, n) {
//        var $childData = dataService.getData(SysConstant.TaskGuid.OrgInfo, $(n).attr("GUID"), Constant.Identify.BranchList);
//        var $childXml = utility.xml.convertXmlStringToDoc($childData);
//        var $childList = $childXml.find("OUDataInfo");
//       // var deptInfo = $(n).attr("Name").split("|");
////        $departJson.push({
////            "id": $(n).attr("GUID"),
////            "code": deptInfo.length > 1 ? deptInfo[0] : i + 1,
////            "name": deptInfo.length > 1 ? deptInfo[1] : deptInfo[0],
////            "state": $childList.length > 0 ? "closed" : undefined,
////            "children": $childList.length > 0 ? pushChildList($childList) : undefined
////        });
//        $departJson.push({
//            "id": $(n).attr("GUID"),
//            "code": isCompany ? "1" : $(n).attr("GUID"),
//            "name": $(n).attr("Name"),
//            "state": $childList.length > 0 ? "closed" : undefined,
//            "children": $childList.length > 0 ? pushChildList($childList) : undefined
//        });
//    });
//    return $departJson;
//}

/////保存文件上传信息
//function uploadFileList($fileList, dataGuid, dataType) {
//    $.each($fileList, function (i, n) {

//        var $FileAttachXml = dataService.fillNewGuid(PrjConstant.GLC.FeeMgr.FileAttachment.Template, "FileAttachmentGuid");
//        $FileAttachXml.find("LocalFileName").text(n.name);
//        $FileAttachXml.find("FilePath").text(n.filePath);

//        var filePath_str = n.filePath.toString();
//        var file_index = filePath_str.lastIndexOf("\\");
//        var file_name = filePath_str.substr(file_index + 1, filePath_str.length - file_index - 1);
//        $FileAttachXml.find("FileName").text(file_name);

//        var time_start = filePath_str.lastIndexOf("_");
//        var create_time = filePath_str.substr(time_start + 1, 14);
//        $FileAttachXml.find("CreateDate").text(create_time);
//        $FileAttachXml.find("DataGuid").text(dataGuid);
//        $FileAttachXml.find("DataType").text(dataType);

//        var result = dataService.setData(PrjConstant.PrjTaskGuid.FeeMgr, $FileAttachXml.find("FileAttachmentGuid").text(), PrjConstant.GLC.FeeMgr.FileAttachment.DataType, utility.xml.convertXmlDocToString($FileAttachXml));
//        //utility.message.promptOperationResult("保存", "附件", (submitResult == 0));
//    });
//}

//function generateExcel(title, gridId,dataList) {
//    
//    var ExcelApp = new ActiveXObject("Excel.Application");
//    if (ExcelApp == null || ExcelApp == "") {
//        confirm('输出到Excel需要启用ActiveX控件，请检查是否进行正确设置？');
//        return;
//    }
//    var xlBook = ExcelApp.Workbooks.Add;                         //新增工作簿
//    newBook.Worksheets.Add;
//    newBook.Worksheets(1).Activate; //
//    var columns = $(gridId).datagrid("getColumnFields", true);
//    var j = 0;
//    var colIndexArr = [];
//    $.each(columns, function (i, n) {
//        var opts = $(gridId).datagrid("getColumnOption", n);
//        if (!opts.hidden) {
//            newBook.Worksheets(1).cells(1, j).value = opts.title;
//            j = j + 1;

//        }
//    });
//    $.each(dataList, function (i, n) {


//    });
//    ExcelApp.Visible = true;
//    ExcelApp.UserControl = true;


//}

//function getOUDataInfoListForGrid(dataGuid, dataType) {
//    $data = dataService.getData(SysConstant.TaskGuid.OrgInfo, dataGuid, dataType);
//    $xml = utility.xml.convertXmlStringToDoc($data);
//    $list = $xml.find("OUDataInfo");
//    $json = { total: $list.length, rows: [] };
//    $list.each(function (i, n) {
//        $json.rows.push({ GUID: $(n).attr("GUID"), Name: $(n).attr("Name"), OUType: $(n).attr("OUType"), CompanyGuid: $(n).attr("CompanyGuid") });
//    });
//    return $json;
//}
//var _exportExcel = function () {
//    alert("导出EXCEL");
//    var tableid = "orders";
//    var curTbl = "aaa";
//    var oXL = null;
//    try {
//        oXL = GetObject("", "Excel.Application");
//    } catch (E) {
//        try {
//            oXL = new ActiveXObject("Excel.Application");
//        } catch (E2) {
//            alert("请确认:\n1.安装Microsoft Excel.\n2.设置浏览器安全级别：Internet 选项=>安全=>自定义级别 \n \"将ActiveX控件启用\"");
//            return;
//        }
//    }
//    // 创建AX对象excel 
//    var oWB = oXL.Workbooks.Add();
//    // 获取workbook对象 
//    var oSheet = oWB.ActiveSheet;
//    // 在此进行样式控制 
//    oSheet.Rows(1 + ":" + 1).RowHeight = 20; // 定义行高 
//    oSheet.Rows(2 + ":" + 2).RowHeight = 30;
//    // 定义列宽 
//    oSheet.Columns('A:A').ColumnWidth = 5;
//    oSheet.Columns('B:B').ColumnWidth = 10;
//    oSheet.Columns('C:C').ColumnWidth = 15;
//    oSheet.Columns('D:D').ColumnWidth = 15;
//    oSheet.Columns('E:E').ColumnWidth = 20;
//    oSheet.Columns('F:F').ColumnWidth = 12;
//    oSheet.Columns('G:G').ColumnWidth = 15;
//    oSheet.Columns('H:H').ColumnWidth = 15;
//    oSheet.Columns('I:I').ColumnWidth = 15;
//    oSheet.Columns('J:J').ColumnWidth = 15;
//    oSheet.Columns('K:K').ColumnWidth = 15;
//    oSheet.Columns('L:L').ColumnWidth = 15;
//    oSheet.Columns('M:M').ColumnWidth = 5;
//    oSheet.Columns('N:N').ColumnWidth = 5;
//    oSheet.Columns('O:O').ColumnWidth = 15;

//    oSheet.Rows(1).HorizontalAlignment = 3;

////    var sel = document.body.createTextRange(); // 激活当前sheet 
////    sel.moveToElementText(curTbl); // 把表格中的内容移到TextRange中 
////    sel.select(); // 全选TextRange中内容 
////    sel.execCommand("Copy"); // 复制TextRange中内容 
//    oSheet.Paste(); // 粘贴到活动的EXCEL中 
//    oXL.Visible = true; // 设置excel可见属性 
//    oSheet.Application.Quit(); // 结束当前进程 
//  //  window.opener = null;
//}